import React, { useState } from 'react';
import _ from 'lodash';
import { useTranslation } from 'react-i18next';
import { Popover, Progress, Space, Spin, Tooltip } from 'antd';
import Icon, { PlusCircleOutlined, CloseCircleOutlined, CalendarOutlined, QuestionOutlined, MinusCircleOutlined } from '@ant-design/icons';
import type { CustomIconComponentProps } from '@ant-design/icons/lib/components/Icon';
import { getFieldLabel } from '../../Elasticsearch/utils';
import { dslBuilder } from '../../Elasticsearch/utils';
import { getFieldValues, typeMap } from '../../Elasticsearch/services';
import { Field as FieldType, Filter } from '../services';

interface Props {
  item: string;
  record: FieldType;
  type: 'selected' | 'available';
  fieldConfig?: any;
  params?: any;
  onSelect?: (field: string) => void;
  onRemove?: (field: string) => void;
  filters?: Filter[];
  onValueFilter?: (Filter) => void;
}

const operIconMap = {
  selected: <CloseCircleOutlined data-oid='vwk41he' />,
  available: <PlusCircleOutlined data-oid='qewqi3n' />,
};

const FieldBooleanSvg = () => (
  <svg width='1em' height='1em' fill='currentColor' viewBox='0 0 76 76' data-oid='.tt5p-f'>
    <path
      d='M 36,23L 30,23L 30,40L 25,40L 25,23L 19,23L 19,19L 36,19L 36,23 Z M 57,40L 50,40L 50,45L 56,45L 56,49L 50,49L 50,57L 45,57L 45,36L 57,36L 57,40 Z M 44,19L 48.5,19L 32.5,57L 28,57L 44,19 Z '
      data-oid='ljj86.f'
    />
  </svg>
);

const FieldBooleanIcon = (props: Partial<CustomIconComponentProps>) => <Icon component={FieldBooleanSvg} {...props} data-oid='wwb.lzw' />;

export const typeIconMap = {
  string: (
    <span className='n9e-es-discover-fields-item-field' style={{ color: '#4a7194' }} data-oid='nw:flwm'>
      t
    </span>
  ),

  number: (
    <span className='n9e-es-discover-fields-item-field' style={{ color: '#387765' }} data-oid='-8b:7jb'>
      #
    </span>
  ),

  date: <CalendarOutlined style={{ color: '#7b705a' }} data-oid='ai0g2lt' />,
  boolean: <FieldBooleanIcon style={{ color: '#996130', fontSize: 18 }} data-oid='_s23vpw' />,
};

export default function Field(props: Props) {
  const { t } = useTranslation('explorer');
  const { item, record, type, fieldConfig, params, onSelect, onRemove, filters, onValueFilter } = props;
  const { form, timesRef, datasourceValue, limit } = params;
  const [top5Visible, setTop5Visible] = useState<boolean>(false);
  const [top5Data, setTop5Data] = useState<any[]>([]);
  const [top5Loading, setTop5Loading] = useState<boolean>(false);
  const fieldLabel = getFieldLabel(item, fieldConfig);

  return (
    <Popover
      placement='right'
      trigger={['click']}
      overlayInnerStyle={{
        width: 240,
        height: 240,
      }}
      visible={top5Visible}
      title={fieldLabel}
      content={
        <div className='n9e-es-discover-field-values-topn' data-oid='dm6_vwd'>
          <strong data-oid='d557wz9'>{t('log.fieldValues_topn')}</strong>
          <Spin spinning={top5Loading} data-oid='qf7lwq_'>
            <div className='n9e-es-discover-field-values-topn-list' data-oid='-ej-x.v'>
              {_.isEmpty(top5Data) && t('log.fieldValues_topnNoData')}
              {_.map(top5Data, (item) => {
                const percent = _.floor(item.value * 100, 2);
                return (
                  <div key={item.label} className='n9e-es-discover-field-values-topn-item' data-oid='mez5_54'>
                    <div style={{ width: 'calc(100% - 40px)' }} data-oid='fk_.jb7'>
                      <div className='n9e-es-discover-field-values-topn-item-content' data-oid='cbdm2fv'>
                        <div className='n9e-es-discover-field-values-topn-item-label' data-oid='r3j5y26'>
                          {_.isEmpty(item.label) && !_.isNumber(item.label) ? (
                            '(empty)'
                          ) : (
                            <Tooltip title={item.label} data-oid='kw4jm1e'>
                              {item.label}
                            </Tooltip>
                          )}
                        </div>
                        <div className='n9e-es-discover-field-values-topn-item-percent' data-oid='nb4-0s5'>
                          {percent}%
                        </div>
                      </div>
                      <Progress percent={percent} size='small' showInfo={false} strokeColor='#3375f7' data-oid='.nk:blu' />
                    </div>
                    <div style={{ width: 32 }} data-oid='lbc5ao_'>
                      <Space data-oid='5mvc-zp'>
                        <PlusCircleOutlined
                          onClick={() => {
                            if (onValueFilter) {
                              onValueFilter({
                                key: record.name,
                                value: item.label,
                                operator: 'is',
                              });
                              setTop5Visible(false);
                            }
                          }}
                          data-oid='g92_rh0'
                        />

                        <MinusCircleOutlined
                          onClick={() => {
                            if (onValueFilter) {
                              onValueFilter({
                                key: record.name,
                                value: item.label,
                                operator: 'is not',
                              });
                              setTop5Visible(false);
                            }
                          }}
                          data-oid='7bdhvhj'
                        />
                      </Space>
                    </div>
                  </div>
                );
              })}
            </div>
          </Spin>
        </div>
      }
      onVisibleChange={(visible) => {
        setTop5Visible(visible);
        if (visible) {
          setTop5Loading(true);
          const values = form.getFieldsValue();
          try {
            getFieldValues(
              datasourceValue,
              dslBuilder({
                index: values.query.index,
                date_field: values.query.date_field,
                ...timesRef.current,
                filters,
                syntax: values.query.syntax,
                query_string: values.query.filter,
                kuery: values.query.filter,
                limit,
                fields: [item],
              }),
              item,
            )
              .then((res) => {
                setTop5Data(res);
              })
              .finally(() => {
                setTop5Loading(false);
              });
          } catch (e) {
            console.error(e);
            setTop5Loading(false);
          }
        } else {
          setTop5Data([]);
        }
      }}
      data-oid='htuuqo_'
    >
      <div className='n9e-es-discover-fields-item' key={item} data-oid='esos0o2'>
        <span className='n9e-es-discover-fields-item-icon' data-oid=':rx5.y.'>
          {typeIconMap[typeMap[record.type]] || <QuestionOutlined data-oid='.rva:-.' />}
        </span>
        <span className='n9e-es-discover-fields-item-content' data-oid='vd92.m.'>
          {fieldLabel}
        </span>
        <span
          className='n9e-es-discover-fields-item-oper'
          onClick={() => {
            if (type === 'selected' && onRemove) {
              onRemove(item);
            } else if (type === 'available' && onSelect) {
              onSelect(item);
            }
          }}
          data-oid='b__t6zw'
        >
          {operIconMap[type]}
        </span>
      </div>
    </Popover>
  );
}
